class Solution:
    def minDominoRotations(self, A: list, B: list) -> int:
        def majority(array):
            candidate = -1
            votes = 0
            for i in range(len(array)):
                if votes == 0:
                    candidate = array[i]
                if candidate == array[i]:
                    votes += 1
                else:
                    votes -= 1
            
            return candidate

        def change_count(source, target, num):
            res = 0
            for i in range(len(source)):
                if source[i] != num:
                    if target[i] != num:
                        return -1
                    res += 1
            return res

        a_majority = majority(A)
        b_majority = majority(B)
        a_change_count = change_count(A, B, a_majority)
        b_change_count = change_count(B, A, b_majority)

        if a_change_count == -1:
            return b_change_count
        if b_change_count == -1:
            return a_change_count

        return min(a_change_count, b_change_count)
